﻿using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace ST.Torch.WebApi.Web.Core;

public class JwtHandler : AppAuthorizeHandler
{

        /// <summary>
        /// 重写 Handler 添加自动刷新收取逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task HandleAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            // 自动刷新 token
            if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext()))
                await AuthorizeHandleAsync(context);
            else context.Fail();    // 授权失败
        }
        public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            // 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false

            //return Task.FromResult(true);
            //return await CheckAuthorzieAsync(httpContext);
            return Task.FromResult(CheckAuthorzieAsync(httpContext));
        }

    /// <summary>
    /// 检查权限
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    private static bool CheckAuthorzieAsync(DefaultHttpContext httpContext)
    {
        
            // 获取权限特性
            var securityDefineAttribute = httpContext.GetMetadata<SecurityDefineAttribute>();
            if (securityDefineAttribute == null) return true;

            // 解析服务
            //var securityContext = httpContext.RequestServices.GetService<ISecurityManage>();
            //var securities = securityContext.CurrentModules;
            //var securities = App.GetService<ISecurityManage>().CurrentModules;
            // 检查授权
            //return securities.Select(u => u.NameKey).Contains(securityDefineAttribute.ResourceId);

        
        return false;

    }


}
